package com.hanrui.android.net.presenter.message.audit;

import android.content.Context;
import android.util.Log;

import com.hanrui.android.activity.LoginActivity;
import com.hanrui.android.library.base.BaseBean;
import com.hanrui.android.library.base.BasePresenter;
import com.hanrui.android.constant.Constant;
import com.hanrui.android.constant.LoadType;
import com.hanrui.android.model.ApproveListBean;
import com.hanrui.android.library.net.ApiService;
import com.hanrui.android.library.net.RetrofitManager;
import com.hanrui.android.library.net.RxSchedulers;
import com.hanrui.android.net.contract.message.audit.ApproveContract;

import javax.inject.Inject;

import io.reactivex.functions.Consumer;

/**
 * Created by Administrator on 2018/3/12.
 */

public class ApprovePresenter extends BasePresenter<ApproveContract.View> implements ApproveContract.Presenter {
    private boolean mIsRefresh;

    @Inject
    public ApprovePresenter(){
        this.mIsRefresh = true;
    }

    @Override
    public void loadData(final Context context) {
        RetrofitManager.create(ApiService.class, Constant.baseUrl)
                .list()
                .compose(RxSchedulers.<BaseBean<ApproveListBean>>applySchedulers())
                .compose(mView.<BaseBean<ApproveListBean>>bindToLife())
                .subscribe(new Consumer<BaseBean<ApproveListBean>>() {
                    @Override
                    public void accept(BaseBean<ApproveListBean> dataResponse) throws Exception {
                        Log.e(Constant.tag,dataResponse.getCode()+"");
                        if (dataResponse.getCode() == 1){
                            int loadType = mIsRefresh? LoadType.TYPE_REFRESH_SUCCESS :LoadType.TYPE_LOAD_MORE_SUCCESS;
                            mView.loadData(dataResponse.getData().getActList(),loadType);
                        }else if (dataResponse.getCode() == 201){
                            LoginActivity.start(context);
                            mView.showFaild("会话过期请重新登录");
                        }else {
                            int loadType = mIsRefresh? LoadType.TYPE_REFRESH_ERROR : LoadType.TYPE_LOAD_MORE_ERROR;
                            mView.loadData(null,loadType);
                            mView.showFaild(String.valueOf(dataResponse.getMessage()));
                        }

                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        int loadType = mIsRefresh? LoadType.TYPE_REFRESH_ERROR : LoadType.TYPE_LOAD_MORE_ERROR;
                        mView.loadData(null,loadType);
                        mView.showFaild(throwable.getMessage());
                    }
                });
    }

    @Override
    public void refresh(Context context) {
        mIsRefresh = true;
        loadData(context);
    }
}
